import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_audioplayers.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/utils/file_util.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/modules/application/inventory_system/job_performance_checklist/job_latest_execution_details/job_latest_execution_details_controller.dart';
import 'package:url_launcher/url_launcher.dart';

///最新执行详情
class JobLatestExecutionDetailsPage extends StatelessWidget {
  JobLatestExecutionDetailsPage({super.key});

  final controller = Get.put(JobLatestExecutionDetailsController());
  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (_) {
          return Scaffold(
            appBar: CustomAppBar(
              title: Text(
                '详情',
                style: TextStyle(
                  fontSize: 18.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w400,
                ),
              ),
              leading: const BackButton(
                color: Colors.white,
              ),
              iconButtonColor: Colors.white,
              backgroundColor: const Color(0xFF5C6DFF),
            ),
            body: Container(
                color: const Color(0xFFF5F5F6),
                child: Stack(
                  children: [
                    //台账基础信息
                    _getBasicInformation(),
                    Container(
                      margin: EdgeInsets.only(top: 90.w),
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            _getDetailsView(),
                            AppGaps.vGap16,
                            Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(10.w),
                              ),
                              child: Container(
                                padding: EdgeInsets.fromLTRB(16.w, 20.w, 16.w, 16.w),
                                child: Column(
                                  children: [
                                    ListView.builder(
                                      physics: const ClampingScrollPhysics(),
                                      shrinkWrap: true,
                                      itemCount: controller.getPlanRecordEntity.length,
                                      itemBuilder: (context, index) {
                                        return _itemWidget(index);
                                      },
                                    )
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                )),
          );
        });
  }

  /// 获取台账基础信息视图
  Widget _getBasicInformation() {
    return Container(
      height: 140.w,
      width: AppDimens.sh,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.w),
      color: const Color(0xFF5C6DFF),
      child: Column(
        children: [
          Row(
            children: [
              SvgPicture.asset(
                AppImages.icon_ledger_icon,
                width: 17.w,
                height: 17.w,
              ),
              AppGaps.hGap6,
              Expanded(
                  child: Text(
                controller.data?.workKindName ?? '',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.white,
                  overflow: TextOverflow.ellipsis,
                  fontWeight: FontWeight.w500,
                ),
              )),
            ],
          ),
          AppGaps.vGap12,
          Row(
            children: [
              Expanded(
                child: Row(
                  children: [
                    Text(
                      '巡检描述：',
                      style: TextStyle(
                        overflow: TextOverflow.ellipsis,
                        fontSize: 13.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    Expanded(
                        child: Text(
                      controller.data?.inspectionDescription ?? '',
                      style: TextStyle(
                        overflow: TextOverflow.ellipsis,
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w400,
                      ),
                    )),
                  ],
                ),
              ),
              Container(
                height: 14.w,
                width: 2.w,
                margin: EdgeInsets.only(right: 20.w, left: 10.w),
                decoration: const BoxDecoration(
                    gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
                  Color(0x00ffffff),
                  Color(0xffffffff),
                  Color(0x00ffffff),
                ])),
              ),
              _getExpandButton()
            ],
          )
        ],
      ),
    );
  }

  /// 获取展开按钮
  Widget _getExpandButton() {
    return Row(
      children: [
        Text(
          controller.isExpanded ? '收起' : '展开',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
            fontWeight: FontWeight.w400,
          ),
        ),
        AppGaps.hGap6,
        SvgPicture.asset(
          controller.isExpanded ? AppImages.icon_circle_up : AppImages.icon_circle_down,
          width: 16.w,
          height: 16.w,
        )
      ],
    ).clickOnce(controller.onExpanded);
  }

  Widget _getDetailsView() {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 20.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(
          Radius.circular(6.w),
        ),
      ),
      child: Column(
        children: [
          Row(
            children: [_getFieldView('风险分析对象：', controller.data?.riskObjectName ?? '')],
          ),
          AppGaps.vGap10,
          Row(
            children: [_getFieldView('风险分析单元：', controller.data?.riskUnitName ?? '')],
          ),
          AppGaps.vGap10,
          Row(
            children: [
              _getFieldView('风险事件：', controller.data?.riskEventName ?? ''),
              _getCurrentRiskLevel(),
            ],
          ),
          Visibility(
              visible: controller.isExpanded,
              child: Column(
                children: [
                  AppGaps.vGap10,
                  Row(
                    children: [_getFieldView('风险描述：', controller.data?.riskDescription ?? '')],
                  ),
                  AppGaps.vGap10,
                  Row(
                    children: [
                      _getInitialRiskLevel(),
                      _getFieldView('初始风险度：', '${controller.data?.initialRiskDegree ?? ''}'),
                    ],
                  ),
                  AppGaps.vGap10,
                  Row(
                    children: [
                      _getFieldView('初始风险后果：', controller.data?.initialRiskConsequences ?? ''),
                      _getFieldView('任务周期：', '${controller.data?.checkCycle ?? ''}'),
                    ],
                  ),
                  AppGaps.vGap10,
                  Row(
                    children: [_getFieldView('管控措施：', controller.data?.riskMeasureDesc ?? '')],
                  ),
                ],
              ))
        ],
      ),
    );
  }

  /// 字段显示
  Widget _getFieldView(String title, String value, {Color? rightColor}) {
    return Expanded(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 13.sp,
              height: 1.2,
              color: const Color(0xFFA5A6B5),
              fontWeight: FontWeight.w400,
            ),
          ),
          Expanded(
              child: Text(
            value,
            style: TextStyle(
              fontSize: 13.sp,
              height: 1.2,
              color: rightColor ?? const Color(0xFF495061),
              fontWeight: FontWeight.w400,
            ),
          ))
        ],
      ),
    );
  }


  Widget _itemWidget(int index) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 5.w),
              width: 10.w,
              height: 10.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: _color(index % 4),
                  width: 2.w,
                ),
              ),
            ),
            _bigDivider(),
          ],
        ),
        AppGaps.hGap10,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    '巡检信息',
                    style: TextStyle(fontSize: 15.sp, color: const Color(0xFF5C6DFF)),
                  ),
                  Text(
                    ' / ',
                    style: TextStyle(fontSize: 15.sp, color: const Color(0xFF262F38)),
                  ),
                  Text(
                    ' ${controller.data?.tbBaseDangerInvestigation?.checkAcceptTime ?? ''}',
                    style: TextStyle(fontSize: 12.sp, color: const Color(0xFF262F38)),
                  ),
                ],
              ),
              AppGaps.vGap10,
              Container(
                padding: EdgeInsets.all(10.w),
                decoration: const BoxDecoration(
                  color: Color(0xFFF5F6FF),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text(
                          '巡检结果：',
                          style: TextStyle(color: const Color(0xFFA5A6B5), fontWeight: FontWeight.w400, fontSize: 13.sp),
                        ),
                        Text(
                          //	隐患状态（待确认：-1；整改中：0；待验收：1；已验收：9；驳回：10）
                          _dangerState(controller.data?.tbBaseDangerInvestigation?.dangerState ?? ''),
                          style: TextStyle(color: const Color(0xFF00CE78), fontWeight: FontWeight.w400, fontSize: 12.sp),
                        ),
                      ],
                    ),
                    AppGaps.vGap10,
                    Row(
                      children: [
                        Text(
                          '巡检人：',
                          style: TextStyle(color: const Color(0xFFA5A6B5), fontWeight: FontWeight.w400, fontSize: 13.sp),
                        ),
                        Text(
                          controller.data?.tbBaseDangerInvestigation?.checkAcceptPerson ?? '',
                          style: TextStyle(color: const Color(0xFF495061), fontWeight: FontWeight.w400, fontSize: 12.sp),
                        ),
                      ],
                    ),
                    AppGaps.vGap10,
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '拍照:',
                        style: TextStyle(
                          fontSize: 13.sp,
                          color: AppColors.font_color_gray,
                        ),
                      ),
                    ),
                    AppGaps.vGap8,
                    controller.data != null &&
                            controller.data!.tbBaseDangerInvestigation != null &&
                            controller.data!.tbBaseDangerInvestigation!.dangerVoice!.isNotEmpty
                        ? Align(
                            alignment: Alignment.centerLeft,
                            child: Wrap(
                                spacing: 5.w,
                                children: controller.data!.tbBaseDangerInvestigation!.checkAcceptImages!.map<Widget>((item) {
                                  return Container(
                                    width: 74.w,
                                    height: 74.w,
                                    margin: EdgeInsets.only(bottom: 10.w),
                                    decoration: BoxDecoration(
                                      color: const Color(0xffF7F7FB),
                                      border: Border.all(
                                        color: const Color(0xffEBEDF0),
                                      ),
                                      borderRadius: BorderRadius.circular(8.w),
                                      image: DecorationImage(
                                        image: NetworkImage(Interface.fileUrl + item),
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  ).clickShowLarge(url: Interface.fileUrl + item);
                                }).toList()),
                          )
                        : SizedBox(
                            width: 74.w,
                            height: 74.w,
                          ),
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '视频:',
                        style: TextStyle(
                          fontSize: 13.sp,
                          color: AppColors.font_color_gray,
                        ),
                      ),
                    ),
                    AppGaps.vGap8,
                    controller.data != null &&
                            controller.data!.tbBaseDangerInvestigation != null &&
                            controller.data!.tbBaseDangerInvestigation!.dangerVideo!.isNotEmpty
                        ? Align(
                            alignment: Alignment.centerLeft,
                            child: Wrap(
                                spacing: 5.w,
                                children: controller.data!.tbBaseDangerInvestigation!.dangerVideo!.map<Widget>((item) {
                                  return Container(
                                    width: 160.w,
                                    height: 90.w,
                                    margin: const EdgeInsets.only(bottom: 10),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      color: const Color(0xff060B15),
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: IconButton(
                                      icon: const Icon(
                                        Icons.play_circle,
                                        color: Colors.white,
                                        size: 30,
                                      ),
                                      onPressed: () {
                                        FileUtils.openFile(Interface.fileUrl + item);
                                      },
                                    ),
                                  );
                                }).toList()),
                          )
                        : SizedBox(
                            width: 160.w,
                            height: 90.w,
                          ),
                    AppGaps.vGap8,
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        '语音:',
                        style: TextStyle(
                          fontSize: 13.sp,
                          color: AppColors.font_color_gray,
                        ),
                      ),
                    ),
                    AppGaps.vGap8,
                    controller.data != null &&
                            controller.data!.tbBaseDangerInvestigation != null &&
                            controller.data!.tbBaseDangerInvestigation!.dangerVoice!.isNotEmpty
                        ? CustomAudioplayers(
                            audioUrl: controller.data!.tbBaseDangerInvestigation!.dangerVoice!,
                            isEnabled: false,
                          )
                        : SizedBox(
                            width: 30.w,
                            height: 50.w,
                          ),
                  ],
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  Color _color(int index) {
    switch (index) {
      case 1:
        return const Color(0xFFFD6B6B);
      case 2:
        return const Color(0xFFFC9900);
      case 3:
        return const Color(0xFF5C6DFF);
      default:
        return const Color(0xFFFD6B6B);
    }
  }

  ///分割线
  Widget _bigDivider() {
    return Container(
      width: 1.w,
      height: 428.w,
      decoration: const BoxDecoration(
          gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
        Color(0x00557CFD),
        Color(0xCC557CFD),
      ])),
    );
  }

  /// 当前风险等级
  Widget _getCurrentRiskLevel() {
    String name = '';
    Color? rightColor;
    switch (controller.data?.currentRiskLevel) {
      case '1':
        name = '重大风险';
        rightColor = const Color(0xffFD6B6B);
        break;
      case '2':
        name = '较大风险';
        rightColor = const Color(0xffFD6B6B).withOpacity(0.7);
        break;
      case '3':
        name = '一般风险';
        rightColor = const Color(0xffFFCE24);
        break;
      case '4':
        name = '低风险';
        rightColor = const Color(0xFF5C6DFF);
        break;
      default:
        break;
    }
    return _getFieldView('当前风险等级：', name, rightColor: rightColor);
  }

  /// 初始风险等级
  Widget _getInitialRiskLevel() {
    String name = '';
    Color? rightColor;
    switch ('${controller.data?.initialRiskPossibility}') {
      case '1':
        name = '重大风险';
        rightColor = const Color(0xffFD6B6B);
        break;
      case '2':
        name = '较大风险';
        rightColor = const Color(0xffFD6B6B).withOpacity(0.7);
        break;
      case '3':
        name = '一般风险';
        rightColor = const Color(0xffFFCE24);
        break;
      case '4':
        name = '低风险';
        rightColor = const Color(0xFF5C6DFF);
        break;
      default:
        break;
    }
    return _getFieldView('初始风险等级：', name, rightColor: rightColor);
  }

  ///	隐患状态（待确认：-1；整改中：0；待验收：1；已验收：9；驳回：10）
  String _dangerState(String s) {
    switch (s) {
      case '0':
        return '整改中';
      case '1':
        return '待验收';
      case '9':
        return '已验收';
      case '10':
        return '驳回';
      case '-1':
        return '待确认';
      default:
        return '';
    }
  }
}
